#ifndef ASR_H
#define ASR_H

#include <QWidget>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QHostInfo>
#include <QTimer>

class Asr : public QWidget
{
    Q_OBJECT

public:
    explicit Asr(QWidget *parent = nullptr);
    ~Asr();

    void getTheResult(const QString &fileName);

signals:
    void asrReadyData(const QString &result);

private slots:
    void handleNetworkReply(QNetworkReply *reply);

private:
    void requestToken();
    void sendSpeechRequest(const QByteArray &jsonData);
    void processAudioFile(const QString &fileName);
    void processTokenResponse(const QByteArray &data);
    void processSpeechResponse(const QByteArray &data);
    bool verifyAudioFormat(const QString &fileName, int &outSampleRate);
    bool resampleAudio(const QString &inputFile, const QString &outputFile, int targetRate);

    QNetworkAccessManager *networkAccessManager;
    QString accessToken;
    QString pendingAudioFile;
    QString serverApiUrl;
    bool isProcessing = false;

    const QString tokenUrl = "https://aip.baidubce.com/oauth/2.0/token?"
                            "grant_type=client_credentials&"
                            "client_id=3QpFxljvJM72iEKqzrvNw8kO&"
                            "client_secret=lRf1sKp0cLTFeZjn7E8L9WhrAyW7JUJt";

    const QString serverApiTemplate = "http://vop.baidu.com/server_api?dev_pid=1537&cuid=%1&token=%2";
};

#endif // ASR_H
